package com.cxs.template;

import com.cxs.handler.ResultHandler;
import com.cxs.utils.DbUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @Project: jdbc
 * @Author: cxs2014501@163.com
 * @Create: 2022/8/31 16:13
 * @Description:
 **/
public class JdbcTemplate {
    public static Integer executeDMLSql(String sql, Object... params){
        Connection connection = null;
        PreparedStatement statement = null;
        Integer result = 0;
        try {
            connection = DbUtil.getConnection();
            statement = connection.prepareStatement(sql);
            if (null != params && params.length > 0) {
                for (int i = 0; i < params.length; i++) {
                    statement.setObject(i+1, params[i]);
                }
            }
            result = statement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DbUtil.close(connection, statement, null);
        }
        return result;
    }

    public static <T> T executeDQLSql(String sql, ResultHandler<T> handler, Object... params){
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        T result = null;
        try {
            connection = DbUtil.getConnection();
            statement = connection.prepareStatement(sql);
            if (null != params && params.length > 0) {
                for (int i = 0; i < params.length; i++) {
                    statement.setObject(i+1, params[i]);
                }
            }
            resultSet = statement.executeQuery();
            result = handler.resultHandle(resultSet);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DbUtil.close(connection, statement, resultSet);
        }
        return result;
    }
}
